#include <common.h>
#include <malloc.h>
#include <linux/string.h>
#include "zipfile.h"
#include "zip_api.h"

int UnzipFileByName(ZIPDATA *pZipData, const char *i_filename)
{
	Zipfile z_file;
	int ret, isFindFile=0;
	unsigned int unSize;
	
	memset(&z_file, 0, sizeof(Zipfile));
	ret = zipfile_init(&z_file, pZipData->pCmpData, pZipData->cmpDataLen, i_filename);
	if (ret != OK)
	{
		printf("[%s] %d, source file error\r\n", __func__, __LINE__);
		return ret;
	}

	for (zipfile_beging(&z_file); !zipfile_is_end(&z_file); zipfile_advance(&z_file))
	{
		printf("finded: %s\n",z_file.entries.fileName);
		if (0 == memcmp(i_filename, z_file.entries.fileName, z_file.entries.fileNameLength))
		{
			printf("find the dest file:%s, success!\r\n", i_filename);
			isFindFile = 1;
			break;
		}
	}

	if(!isFindFile)
	{
		printf("find the dest file:%s, failed!!\r\n", i_filename);
		return -1;
	}

	unSize = z_file.entries.uncompressedSize;
	pZipData->unCmpDataLen = unSize;
	
	//unSize *= 1.001;	//ensure uncompress buf enough
	unSize = (1000*unSize + unSize)/1000;

	if(pZipData->pUnCmpData == NULL)
		pZipData->pUnCmpData = (char *)malloc(unSize);
	if(pZipData->pUnCmpData == NULL)
	{
		printf("malloc uncompress buf failed!\r\n");
		return -1;
	}
	
	ret = zipfile_decompress_zipentry(&z_file.entries, pZipData->pUnCmpData, unSize);
	if (ret != OK)
	{
		printf("error decompressing file\r\n");
		return ret;
	}

	return 0;
}
